package tools

import (
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"strconv"
	"strings"
)

/**
rsync -av --progress --delete /mnt/d/project/go/src/awesome-rpc root@ip:/var/www/test
*/
type Rsync struct {
	//目标服务器的地址
	IpAddress string
	//目标服务器端口
	Port int
	//文件源路径
	SourceDir string
	//目标服务器地址
	DestDir string
	//ssh 登录的用户
	SshUser string

	ExcludeString string

	Std *Standard

	TimeOut int
}

/**
上传文件到目标服务器地址
*/
func (rsync *Rsync) Upload() (output string, err error) {
	excludeParams := ""
	ExcludeList := strings.Split(rsync.ExcludeString+"\n"+".git", "\n")
	for _, item := range ExcludeList {
		item = strings.Trim(item, " ")
		if item != "" {
			excludeParams += commonhelper.Format(" --exclude {}", item)
		}
	}
	command := commonhelper.Format("rsync --port={} {} -av --delete {} {}@{}:{} -e \"ssh -o PubkeyAuthentication=yes -o stricthostkeychecking=no\"",
		strconv.Itoa(rsync.Port),
		excludeParams,
		rsync.SourceDir,
		rsync.SshUser,
		rsync.IpAddress,
		rsync.DestDir,
	)
	//command = "ls"
	if rsync.Std == nil {
		res, err := GetKernelDriver().ExecShellOrBash(command, false)
		return res, err
	} else {
		newStd := Standard{
			Stdout: rsync.Std.Stdout,
			StdIn:  &StdIn{},
			Stderr: rsync.Std.Stderr,
		}
		//上传2分钟超时
		res, err := GetKernelDriver().ExecShellOrBashWithStdWriter(command, &newStd, func() (time int, echoWords string, callBack func()) {
			return rsync.TimeOut, "rsync 发送超时耗时,检查您的ssh秘钥是否配置正常,或可在配置页添加--timeout= 来设置超时时间", nil
		})
		return res, err
	}

}
